package com.zeng.sim.support.headStrategy;

import com.zeng.sim.util.ApplicationContextUtil;
import com.zeng.sim.util.SimConstant;

import java.util.Collection;
import java.util.Iterator;

/**
 * 描述信息
 *
 * @author zengwanlin
 * @date 2023-12-25T15:15
 */
public abstract class HeadStrategyFactory {

    public static IHeadStrategy getHeadStrategy(String headStrategyCode) {
        return getHeadStrategy(SimConstant.HeadStrategy.getInstance(headStrategyCode));
    }

    public static IHeadStrategy getHeadStrategy(SimConstant.HeadStrategy headStrategy) {
        Collection<IHeadStrategy> strategies = ApplicationContextUtil.getBeansOfType(IHeadStrategy.class);
        Iterator<IHeadStrategy> iterator = strategies.iterator();
        IHeadStrategy strategy = null;
        while (iterator.hasNext()) {
            strategy = iterator.next();
            if (strategy.support(headStrategy)) {
                return strategy;
            }
        }
        throw new IllegalArgumentException("未知的报文头策略：" + headStrategy.getCode());
    }

    /**
     * 根据请求报文，获取可支持的报文头策略
     * @param msgContent
     * @return
     */
    public static IHeadStrategy getReqHeadStrategy(String msgContent) {
        Collection<IHeadStrategy> strategies = ApplicationContextUtil.getBeansOfType(IHeadStrategy.class);
        Iterator<IHeadStrategy> iterator = strategies.iterator();
        IHeadStrategy strategy = null;
        while (iterator.hasNext()) {
            strategy = iterator.next();
            if (strategy instanceof NoopHeadStrategy) {
                continue;
            }
            if (strategy.support(msgContent)) {
                return strategy;
            }
        }
        NoopHeadStrategy noopHeadStrategy = ApplicationContextUtil.getBean(NoopHeadStrategy.class);
        if (noopHeadStrategy.support(msgContent)) {
            return noopHeadStrategy;
        }
        throw new IllegalArgumentException("没有可支持的报文头策略，消息内容：" + msgContent);
    }

}
